package websocket;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import db.HooldusteenuseTellimus;

public class ChatConnectionPool {
	
	private static List<ChatConnection> connections = new ArrayList<ChatConnection>();
	
	public static void addConnection(ChatConnection con){	
		connections.add(con);
	}
	
	public static void removeConnection(ChatConnection con){	
		connections.remove(con);
	}
	public static void broadcastMessage(String message, List<String> to, String from){	
		for(ChatConnection c : connections){
			if(to == null || to.contains(c.group)){
				try {
					c.getWsOutbound().writeTextMessage(CharBuffer.wrap(from+": "+message));
				} catch (IOException e) {				
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void sendNotification(HooldusteenuseTellimus t){
	    StringBuilder b = new StringBuilder("Saabus uus tellimus kasutajalt ");
	    b.append(t.getKinnistu().getYyrnik().getKasutajanimi());
	    b.append(". <br><a href='/websocket/order?id="+t.getHooldusteenuseTellimuseNr()+"'>Vaata tellimust</a>");
	    broadcastMessage("newOrder#"+b.toString(), Arrays.asList("Klienditeenindaja"), "");
	}
}
